package com.thorqq.wuxibusgui;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AES
{
    final String    KEY_ALGORITHM = "AES";
    final String    algorithmStr  = "AES/CBC/NoPadding";
    private Cipher  cipher;
    private boolean isInited      = false;
    private Key     key;

    public static byte[] paddingContent(byte[] src)
    {
        if (src.length % 16 != 0)
        {
            int j = src.length % 16;
            byte[] dest = new byte[src.length + (16 - j)];
            System.arraycopy(src, 0, dest, 0, src.length);
            byte[] tail = new byte[16 - j];
            int i = 0;
            while (i < 16 - j)
            {
                tail[i] = ((byte) (16 - j));
                i += 1;
            }
            System.arraycopy(tail, 0, dest, src.length, tail.length);
            return dest;
        }
        return src;
    }

    public byte[] decrypt(byte[] src, byte[] key)
    {
        init(key);
        try
        {
            this.cipher.init(Cipher.PRIVATE_KEY, this.key, new IvParameterSpec(Constants.IV.getBytes()));
            return this.cipher.doFinal(src);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    public byte[] encrypt(byte[] src, byte[] key)
    {
        src = paddingContent(src);
        init(key);
        try
        {
            this.cipher.init(1, this.key, new IvParameterSpec(Constants.IV.getBytes()));
            return this.cipher.doFinal(src);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    public void init(byte[] paramArrayOfByte)
    {
        if(isInited)
        {
            return;
        }
        
        Security.addProvider(new BouncyCastleProvider());
        this.key = new SecretKeySpec(paramArrayOfByte, "AES");
        try
        {
            this.cipher = Cipher.getInstance("AES/CBC/NoPadding", "BC");
            return;
        }
        catch (NoSuchAlgorithmException ex)
        {
            ex.printStackTrace();
            return;
        }
        catch (NoSuchPaddingException ex)
        {
            ex.printStackTrace();
            return;
        }
        catch (NoSuchProviderException ex)
        {
            ex.printStackTrace();
        }
        
        isInited = true;
    }
}
